package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkSpaceService workSpaceService;


    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
        //统计从begin到end的日期列表
        List<LocalDate> dateList = getDateList(begin, end);
        //根据时间列表查询当天的营业额
        List<Double> turnoverList = new ArrayList<>();
        //遍历时间列表
        for (LocalDate localDate : dateList) {
            //根据当天日期获取到当天的区间
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //创建map存放数据
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.getSumByDate(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        return TurnoverReportVO.builder().
                dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(dateList, ","))
                .build();
    }

    /**
     * 用户量统计
     *
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUsers(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDateList(begin, end);
        //用localdate转换为localdatetime
        //创建当天新增用户列表
        //select count(id) from user where crete_time > ? and create_time < ?;
        List<Integer> newUserList = new ArrayList<>();
        //创建截止用户总量列表
        //select count(id) from user where crete_time > ? and create_time < ?
        List<Integer> sumUserList = new ArrayList<>();
        //根据当天日期获取到当天的区间
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //封装到map中
            Map map = new HashMap();
            map.put("end", endTime);
            //动态sql查询,截止今天的用户总量
            Integer newUser = userMapper.getUserSumByDate(map);
            newUserList.add(newUser);
            map.put("begin", beginTime);
            Integer sumUser = userMapper.getUserSumByDate(map);
            sumUserList.add(sumUser);
        }

        return UserReportVO.builder().
                dateList(StringUtils.join(dateList, ",")).
                newUserList(StringUtils.join(newUserList, ",")).
                totalUserList(StringUtils.join(sumUserList, ",")).
                build();
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //获取日期列表
        List<LocalDate> dateList = getDateList(begin, end);
        //订单总数列表
        List<Integer> orders = new ArrayList<>();
        //有效订单列表
        List<Integer> validOrders = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //sql: select count(id) from orders where order_time>beginTime and order_time<endTime and status = ?
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            Integer ordercount = orderMapper.countOrders(map);
            orders.add(ordercount);
            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = orderMapper.countOrders(map);
            validOrders.add(validOrderCount);
        }
        //统计订单总数和有效订单总数
        Integer sumOrders = orders.stream().reduce(Integer::sum).get();
        Integer sumValidOrders = validOrders.stream().reduce(Integer::sum).get();
        Double orderCompletionRate = 0.0;
        //        double orderCompletionRate = sumValidOrders / sumOrders;
        if (sumOrders != 0) {
            orderCompletionRate = sumValidOrders.doubleValue() / sumOrders;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCompletionRate(orderCompletionRate)
                .totalOrderCount(sumOrders)
                .validOrderCount(sumValidOrders)
                .orderCountList(StringUtils.join(orders, ","))
                .validOrderCountList(StringUtils.join(validOrders, ",")).build();
    }

    /**
     * 销量排名统计
     *
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
//        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOS = orderMapper.getSalesCount(beginTime, endTime);
//        SalesTop10ReportVO.builder()
//                .nameList(StringUtils.join(goodsSalesDTOS.))
//        List<String> nameList = new ArrayList<>();
//        List<Integer> numberList = new ArrayList<>();
        //分别获得有顺序的菜品和销量列表
//        for (GoodsSalesDTO goodsSalesDTO : goodsSalesDTOS) {
//            nameList.add(goodsSalesDTO.getName());
//            numberList.add(goodsSalesDTO.getNumber());
//        }
        List<String> nameList = goodsSalesDTOS.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = goodsSalesDTOS.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 导出运营数据报表
     *
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //从数据库中查出对应数据,最近30天
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        LocalDateTime beginTime = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(dateEnd, LocalTime.MAX);
        //查询概览数据
        BusinessDataVO businessDate = workSpaceService.getTodayData(beginTime, endTime);
        //获取到输入流对象
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        //基于提供好的模板文件创建一个新的Excel表格对象
        try {
            XSSFWorkbook sheets = new XSSFWorkbook(inputStream);
            //获取一个excel的一个页
            XSSFSheet sheet1 = sheets.getSheet("Sheet1");
            //获取到第二行,填充日期信息
            XSSFRow row1 = sheet1.getRow(1);
            //第二行第二个单元格
            row1.getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);
            //获取第四行，填充营业数据
            XSSFRow sheet3 = sheet1.getRow(3);
            //获取对应单元格
            sheet3.getCell(2).setCellValue(businessDate.getTurnover());
            sheet3.getCell(4).setCellValue(businessDate.getOrderCompletionRate());
            sheet3.getCell(6).setCellValue(businessDate.getNewUsers());
            //获取第五行
            XSSFRow sheet5 = sheet1.getRow(4);
            sheet5.getCell(2).setCellValue(businessDate.getValidOrderCount());
            sheet5.getCell(4).setCellValue(businessDate.getUnitPrice());

            //填充每天的数据,30天循环
            for (int i = 0; i < 30; i++) {
                LocalDate begin = dateBegin.plusDays(i);
                LocalDateTime DateTimeBegin = LocalDateTime.of(begin, LocalTime.MIN);
                LocalDateTime DateTimeEnd = LocalDateTime.of(begin, LocalTime.MAX);
                //获取到当天数据
                BusinessDataVO todayData = workSpaceService.getTodayData(DateTimeBegin, DateTimeEnd);
                //获取到对应行
                XSSFRow sheet1Row = sheet1.getRow(7 + i);
                sheet1Row.getCell(1).setCellValue(begin.toString());
                sheet1Row.getCell(2).setCellValue(todayData.getTurnover());
                sheet1Row.getCell(3).setCellValue(todayData.getValidOrderCount());
                sheet1Row.getCell(4).setCellValue(todayData.getOrderCompletionRate());
                sheet1Row.getCell(5).setCellValue(todayData.getUnitPrice());
                sheet1Row.getCell(6).setCellValue(todayData.getNewUsers());
            }


            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream outputStream = response.getOutputStream();
            sheets.write(outputStream);
            outputStream.close();
            sheets.close();

        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    private List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }
}
